package com.shoy.myapp.common;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.shoy.myapp.app.AppContext;
import com.shoy.myapp.app.Constants;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 工具类
 * Created by shoy on 2015/4/1 0001.
 */
public class Utils {
    private static String userAgent;

    /**
     * 空字符判断
     *
     * @param s 字符串
     * @return 是否为空
     */
    public static boolean isEmpty(String s) {
        return null == s || s.length() == 0 || s.trim().length() == 0;
    }

    /**
     * MD5编码
     *
     * @param input 字符串
     * @return Md5
     */
    public static String md5(String input) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());

            byte byteData[] = md.digest();

            StringBuilder hexString = new StringBuilder();
            for (byte aByteData : byteData) {
                String hex = Integer.toHexString(0xff & aByteData);
                if (hex.length() == 1)
                    hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * 接口参数签名
     *
     * @param mapParam 参数
     * @param sb       url链接
     * @return 签名
     */
    public static String signParam(SortedMap<String, String> mapParam,
                                   StringBuffer sb) {
        Set<Map.Entry<String, String>> entrySet = mapParam.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            try {
                sb.append(entry.getKey()).append("=")
                        .append(URLDecoder.decode(entry.getValue(), "utf-8"))
                        .append("&");
            } catch (UnsupportedEncodingException e) {
                Log.e(Constants.TAG, e.getMessage());
                e.printStackTrace();
            }
        }
        // 注意+
        String beforeSignStr = sb.substring(0, sb.length() - 1) + "+"
                + Constants.PARTNER_KEY;
        return md5(beforeSignStr);
    }

    /**
     * 获取返回的实体对象
     *
     * @param context context
     * @param json    json
     * @param tClass  class
     * @param <T>     泛型T
     * @return T
     */
    public static <T> T getResult(Context context, JSONObject json,
                                  Class<T> tClass) {
        try {
            boolean status = json.getBoolean(Constants.RESULT_STATUS);
            if (!status) {
                Toast.makeText(context, json.getString(Constants.RESULT_DESC),
                        Toast.LENGTH_SHORT).show();
                return null;
            }
            JSONObject data = json.getJSONObject(Constants.RESULT_DATA);
            if (data == null)
                return null;
            return JSON.toJavaObject(data, tClass);
        } catch (JSONException e) {
            Toast.makeText(context, "返回数据格式异常！", Toast.LENGTH_SHORT)
                    .show();
            return null;
        }
    }

    /**
     * 获取返回的列表对象
     *
     * @param context context
     * @param json    json
     * @param tClass  class
     * @param <T>     泛型T
     * @return T
     */
    public static <T> List<T> getResults(Context context, JSONObject json,
                                         Class<T> tClass) {
        try {
            boolean status = json.getBoolean(Constants.RESULT_STATUS);
            if (!status) {
                Toast.makeText(context, json.getString(Constants.RESULT_DESC),
                        Toast.LENGTH_SHORT).show();
                return null;
            }
            JSONArray data = json.getJSONArray(Constants.RESULT_DATA);
            if (data == null)
                return new ArrayList<T>();
            return JSON.parseArray(data.toJSONString(), tClass);
        } catch (JSONException e) {
            Toast.makeText(context, "返回数据格式异常！", Toast.LENGTH_SHORT)
                    .show();
            return null;
        }
    }

    /**
     * 获取缩略图
     *
     * @param url    基础图片 路径
     * @param width  宽度
     * @param height 高度
     * @return 缩略图地址
     */
    public static String makeThumb(String url, int width, int height) {
        if (url == null || url.equals(""))
            return url;
        width = (width <= 0 ? 120 : width);
        String fileName = url;
        String ext = fileName.substring(fileName.lastIndexOf("."));
        Log.d(Constants.TAG, "图片后缀名：" + ext);
        if (ext.isEmpty())
            return fileName;
        fileName = url.replaceAll(ext, "_s" + width + "x" + (height <= 0 ? "auto" : height) + ext);
        return fileName;
    }

    /**
     * 根据手机分辨率从dp转成px
     *
     * @param context 当前实例
     * @param dpValue dp
     * @return px
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取版本
     *
     * @param context 当前实例
     * @return 版本
     */
    public static String getVersion(Context context) {
        try {
            PackageInfo manager = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return manager.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "Unknown";
        }
    }

    /**
     * 显示提示信息
     *
     * @param toast   信息
     * @param context 当前实例
     */
    public static void showToast(final String toast, final Context context) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }).start();
    }

    /**
     * 连接状态
     *
     * @param context 当前实例
     * @return 是否连接
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conn.getActiveNetworkInfo();
        return (info != null && info.isConnectedOrConnecting());
    }

    /**
     * 获取客户端环境
     *
     * @return 客户端环境
     */
    public static String getUserAgent(Context context) {
        if (isEmpty(userAgent)) {
            StringBuilder ua = new StringBuilder(Constants.APP_NAME);
            AppContext app = (AppContext) context.getApplicationContext();
            PackageInfo appInfo = app.getPackageInfo();
            if (appInfo != null) {
                //版本信息
                ua.append("/").append(appInfo.versionName).append("_").append(appInfo.versionCode);
            }
            //手机系统版本
            ua.append("/android ").append(android.os.Build.VERSION.RELEASE);
            //手机型号
            ua.append("/").append(android.os.Build.MODEL);
            //客户端唯一标识
            ua.append("/").append(app.getAppId());
            userAgent = ua.toString();
        }
        return userAgent;
    }
}
